//
//  WHWebTools.swift
//  8.31-WH微博
//
//  Created by 吴涵 on 15/9/2.
//  Copyright © 2015年 wuhan. All rights reserved.
//

import UIKit

import AFNetworking
import ReactiveCocoa

enum RequestMethod:String{

    case GET = "GET"
    
    case POST = "POST"
}


class WHWebTools: AFHTTPSessionManager {
    private let clientId = "1626315343"
    private let appSecret = "2488e42fbfe3226bb7ae7c68856e2e2d"
     let redirectUrl = "http://www.baidu.com"
    
//  static  var sharedTools:WHWebTools = WHWebTools()
    static  let sharedTools: WHWebTools = {
    
        var instance = WHWebTools(baseURL: nil)
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    /// MARK: - url
    /// - see: [https://api.weibo.com/oauth2/authorize](https://api.weibo.com/oauth2/authorize)
    
    var url:NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    func loadStatus() -> RACSignal {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        return request(.GET, URLString: urlString, parameters: nil)
    
    }
    func loadAccessToken(code: String) ->RACSignal{
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri":redirectUrl]
//        //测试返回的数据
//        responseSerializer = AFHTTPResponseSerializer()
//        POST(urlString, parameters: params, success: { (_, result) -> Void in
//            printLog(result)
//            
//            let string = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            printLog(string)
//            }, failure: nil)
//        return RACSignal.empty()
        return request(.POST, URLString: urlString, parameters: params,withToken: false)
    }
    
    func loadUserInfo(uid: String) -> RACSignal{
    let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid":uid]
        
        return request(.GET, URLString: urlString, parameters: params)
    }
  
    private func request(method: RequestMethod, URLString: String, var parameters: [String: AnyObject]?,withToken: Bool = true) ->RACSignal{
    return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
        
        if withToken{
            guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
            
                subscriber.sendError(NSError(domain: "wuhan2123--domain error", code: -1001, userInfo: ["errorMessage":"token为空"]))
                
                return nil
            }
            if parameters == nil{
                parameters = [String: AnyObject]()
            }
            parameters!["access_token"] = token
        }
        
        let successCallBack = {(task: NSURLSessionDataTask,result: AnyObject) -> Void in
            subscriber.sendNext(result)
            
            subscriber.sendCompleted()
        }
        let failureCallBack = {(task: NSURLSessionDataTask,error: NSError) -> Void in
            subscriber.sendError(error)
        }
        if method == .GET {
        self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
        }else{
        self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
        }
        return nil
    })
    }

}
